package com.opgea.crm.web.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;


import com.opgea.crm.common.constant.ApplicationConstant;
import com.opgea.crm.common.vo.UserPersonalInfoVo;
import com.opgea.crm.domain.entities.Employee;
import com.opgea.crm.domain.entities.Employeeemails;
import com.opgea.crm.domain.entities.Employeephones;
import com.opgea.crm.domain.entities.security.Authority;
import com.opgea.crm.domain.entities.security.CrmUser;
import com.opgea.crm.domain.entities.security.Group;
import com.opgea.crm.domain.modal.JsonModelMap;
import com.opgea.crm.domain.modal.MailModel;
import com.opgea.crm.services.CompanyService;
import com.opgea.crm.services.EmployeeService;
import com.opgea.crm.services.mail.MailService;
import com.opgea.crm.services.security.AuthorityService;
import com.opgea.crm.services.security.CrmUserService;
import com.opgea.crm.services.security.GroupService;
import com.opgea.crm.services.security.RoleService;
import com.opgea.crm.web.form.LoginDetailsForm;
import com.opgea.crm.web.form.UserPersonalInfoForm;
import com.opgea.crm.web.modal.LoggedUser;

@RequestMapping(value="userManager")
@Controller
public class UserManagerController {

	@Autowired
	EmployeeService empService;
	@Autowired
	CompanyService companyService;
	@Autowired
	CrmUserService userService;
	@Autowired
	RoleService roleService;
	@Autowired
	GroupService groupService;
	@Autowired
	AuthorityService authorityService;
	@Autowired
	MailService mailService;
	
	@RequestMapping(method=RequestMethod.GET)
	public String show(){
		return "userManager";
	}
	
	@RequestMapping(value= "save", method = RequestMethod.POST)
	public @ResponseBody
	Map<String, Object> save(@RequestBody UserPersonalInfoForm form,
			                 @RequestParam(required=true, value="action")String action, HttpServletRequest request){
		
		
		
		Employee emp = null;
                List<Employeephones> empPhones = null;
		List<Employeeemails> emails = null;
		
		Employeephones phone1 = new Employeephones();
		Employeephones phone2 = new Employeephones();
		Employeephones phone3 = new Employeephones();
		Employeephones phone4 = new Employeephones();
		
		Employeeemails email = new Employeeemails();
		if(action.equalsIgnoreCase("save")){
			emp = new Employee();
			empPhones = new ArrayList<Employeephones>();
			emails = new ArrayList<Employeeemails>();
		}
		if(action.equalsIgnoreCase("update")){
			System.out.println("Action : "+action);
			emp = empService.find(form.getEmployeeId());
			System.out.println("EmployeeId : "+form.getEmployeeId());
			System.out.println("Employee : "+emp);
			empPhones = new ArrayList<Employeephones>(emp.getEmployeephonesCollection());
			empPhones.clear();
			emails = new ArrayList<Employeeemails>(emp.getEmployeeemailsCollection());
			emails.clear();
                }
		emp.setFirstName(form.getFirstName());
		emp.setMiddleInitial(form.getMiddleInitial());
		emp.setLastName(form.getLastName());
		emp.setTitle(form.getTitle());
		

		if(form.getEmployeeType() != null){
			emp.setEmployeeType(ApplicationConstant.EmployeeQualifier.CLIENT.ordinal());
		}
		else{
			emp.setEmployeeType(ApplicationConstant.EmployeeQualifier.INTERNAL.ordinal());
		}

		//for phones
		phone1.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Work.ordinal());
                phone1.setPhoneNo(form.getPhone1());
                phone1.setEmployee(emp);

                phone2.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Mobile.ordinal());
                phone2.setPhoneNo(form.getPhone2());
                phone2.setEmployee(emp);

                phone3.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Home.ordinal());
                phone3.setPhoneNo(form.getPhone3());
                phone3.setEmployee(emp);

                phone4.setPhoneQualifier(ApplicationConstant.PhoneQualifier.Fax.ordinal());
                phone4.setPhoneNo(form.getPhone4());
                phone4.setEmployee(emp);

                empPhones.add(phone1);
                empPhones.add(phone2);
                empPhones.add(phone3);
                empPhones.add(phone4);
    	
    	//for emails
		email.setEmailQualifier(ApplicationConstant.EmailQualifier.Primary.ordinal());
		email.setAddress(form.getEmail());
		email.setEmployee(emp);
		emails.add(email);
		
    	emp.setEmployeephonesCollection(empPhones);
    	emp.setEmployeeemailsCollection(emails);

    	
    	if(action.equalsIgnoreCase("save")){
        	emp.setCreatedBy(LoggedUser.getUser(request));
        	emp.setCreatedAt(new Date());
			empService.create(emp);
		}
		if(action.equalsIgnoreCase("update")){
			empService.update(emp);
		}
		
		return JsonModelMap.success().data(emp.getId());
	}
	
	
	@RequestMapping(value="showUsers",method=RequestMethod.GET)
	public @ResponseBody
	Map<String,Object> showLeads(@RequestParam(required=false) String criteria,
								 @RequestParam(required=false) String value){
		if(criteria != null && value != null){
			List<UserPersonalInfoVo> list = empService.findUserList(criteria, value);
			return JsonModelMap.success().data(list);	
		}else{
			return JsonModelMap.success();
		}
		
	}
	
	@RequestMapping(value="showUserDetails", method=RequestMethod.GET)
	public @ResponseBody 
	Map<String, Object> showUserDetails(@RequestParam(required=false, value="empId" )String empId){
		if(empId != null){
			Employee emp = empService.find(new Long(empId));
			System.out.println("Employee : "+emp);
			Map<String, Object> dataMap = new HashMap<String, Object>();
			dataMap.put("success", "success");
			dataMap.put("data", new UserPersonalInfoForm(emp));
			return dataMap;
		}else{
			return JsonModelMap.success();
		}
	}
	
	@RequestMapping(method = RequestMethod.GET, value = "userSearchCriteriaTypes")
	public @ResponseBody
	Map<String, Object> userSearchCriteriaList() {
		return JsonModelMap.success().data(empService.getUserSearchCriteriaTypes());
	}	
	
	@RequestMapping(method=RequestMethod.GET, value="groupList")
	public @ResponseBody 
	Map<String, Object> resourceListByRole(){
		return JsonModelMap.success().data(groupService.findAllGroupNames());
	}	
	
	@RequestMapping(method = RequestMethod.POST, value = "createLogin")
	public @ResponseBody Map<String, Object> createLogin(@RequestBody LoginDetailsForm form,
														 @RequestParam(required=true, value="empId")String empId,
														 @RequestParam(required=true, value="email")String email,
														 @RequestParam(required=true, value="action")String action,
														 HttpServletRequest request){
		
		System.out.println("Form : "+form);
		Employee employee = empService.find(new Long(empId));
		CrmUser user = null;
		List<Group> groups = null;
		
		if(action.equalsIgnoreCase("create")){
			user = new CrmUser();
			groups = new ArrayList<Group>();
		}
		if(action.equalsIgnoreCase("update")){
			user = userService.findByLoginId(form.getUserName());
			groups = user.getGroups();
			if(groups == null){
				groups = new ArrayList<Group>();
			}
		}
		
		Group group = groupService.find(new Long(form.getPermissionId()));
		groups.clear();
		groups.add(group);
		
		user.setUserName(form.getUserName());
		user.setPassword(form.getPassword());
		user.setEmail(email);
		user.setGroups(groups);
		if(form.getActivate() != null){
			user.setEnabled(true);
		}
		if(form.getActivate() == null){
			user.setEnabled(false);
		}

		user.setEmployee(employee);
		
		if(action.equalsIgnoreCase("create")){
			userService.create(user);
			Authority authority = new Authority();
			authority.setAuthority("ROLE_USER");
			authority.setUsers(user);
			System.out.println(authority);
			authorityService.create(authority);
		}
		if(action.equalsIgnoreCase("update")){
			userService.update(user);
		}

		
		StringBuffer msg = new StringBuffer(user.getUserName());
		sendEmail(email, form.getUserName(), form.getPassword(), request);
		msg.append("<br> Email sent to : "+email);

		return JsonModelMap.success().data(msg);
	}
	
	
	
	@RequestMapping(value="sendEmail", method=RequestMethod.POST)
	public @ResponseBody Map<String, Object> sendEmail( @RequestParam(required=true, value="to")String to,
														@RequestParam(required=true, value="userName")String userName,
														@RequestParam(required=true, value="password")String password,
														HttpServletRequest request){
		/*
		String[] filePath = {
                                      "C:\\attachments\\mydoc.docx",
                                      "C:\\attachments\\sp.jpg"
                                    }; 
		
		MailModel mailModel = new MailModel();
		mailModel.setTo(to);
		mailModel.setFrom(LoggedUser.getUser(request).getEmail());
		mailModel.setSubject("SourcePundit InfoSystem (P) Ltd.");
		mailModel.setBodyText("<html><b>Congratulations!</b> <br><br>" +
								 "Your Login Id has been created for CRM Application as <br>" +
								 "<b>User Name : </b>"+userName+"<br> " +
								 "<b>Password : </b>"+password+"<br> " +
								 "<font color='red'><b><i>Note : This is a test mail.</i></b></font></html>");
		mailModel.setFilePath(filePath);
		
		
		mailService.sendMimeMail(mailModel);
                 * 
                 */
		return JsonModelMap.success().data("success");
	}
}
